package net.bxx2004.pandalib.bukkit.network;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import net.bxx2004.pandalib.PandaLib;
import net.bxx2004.pandalib.bukkit.listener.event.PandaLibExtendEvent;
import org.bukkit.entity.Player;
import org.bukkit.event.Listener;

import java.lang.reflect.Method;

import static org.bukkit.Bukkit.getServer;

public class TMessage implements Listener {
    public final String channel;
    public TMessage(String channel){
        getServer().getPluginManager().registerEvents(this,PandaLib.initPlugin);
        getServer().getMessenger().registerIncomingPluginChannel(PandaLib.initPlugin, channel,
                (channl, player, message) ->
                        PandaLibExtendEvent.callPandaLibEvent(new MessageEvent(new MessageBox(channl,read(message))))
                );
        getServer().getMessenger().registerOutgoingPluginChannel(PandaLib.initPlugin, channel);
        this.channel = channel;
    }
    public void send(Player player,MessageBox box){
        try {
            Class<? extends Player> senderClass = player.getClass();
            Method addChannel = senderClass.getDeclaredMethod("addChannel", String.class);
            addChannel.setAccessible(true);
            addChannel.invoke(player, channel);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ByteBuf buf = Unpooled.wrappedBuffer(box.origin());
        player.sendPluginMessage(PandaLib.initPlugin,channel,buf.array());
    }
    public void send(MessageBox box){
        ByteBuf buf = Unpooled.wrappedBuffer(box.origin());
        getServer().sendPluginMessage(PandaLib.initPlugin,channel,buf.array());
    }
    private String read(byte[] array) {
        ByteBuf buf = Unpooled.wrappedBuffer(array);
        int i = buf.writerIndex();
        byte[] bs = new byte[i];
        buf.getBytes(0, (byte[])bs);
        return new String(bs);
    }
}
